const { blogTypeModel } = require('../models/model/blogType');
const { dataToJSON, dataDeleteOrUpdateRes } = require('../utils/tools');

// 添加
exports.createService = async (data) => {
	return dataToJSON(await blogTypeModel.create(data));
};

// 删除
exports.removeService = async (id) => {
	const res = await blogTypeModel.destroy({ where: { id } });
	return dataDeleteOrUpdateRes(res);
};

// 修改
exports.updateService = async (data, id, next) => {
	const res = await blogTypeModel.update(data, { where: { id } });
	return dataDeleteOrUpdateRes(res);
};

// 查单个
exports.findByIdService = async (id) => {
	const res = await blogTypeModel.findOne({ attributes: { exclude: ['createdAt', 'updatedAt'] }, where: { id } });
	return dataToJSON(res);
};

// 查全部
exports.findByPageService = async () => {
	const res = await blogTypeModel.findAll({ attributes: { exclude: ['createdAt', 'updatedAt'] } });
	return JSON.parse(JSON.stringify(res));
};

/**
 * 更改文章类型中的文章数量
 * @param {*} id 文章类型id
 * @param {*} isAdd 是否增加
 */
exports.articleCountChange = async (id, isAdd = true) => {
	const data = await blogTypeModel.findByPk(id);
	if (!data) return;
	if (isAdd) {
		data.articleCount++;
	} else {
		if (data.articleCount >= 1) {
			data.articleCount--;
		}
	}
	await data.save();
};
